<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Validator;
use App\User;


class AuthController extends BaseController
{
    /** 
     * @param Request $request 
     * @return \Illuminate\Http\JsonResponse 
     */  
    public function authenticate(Request $request)  
    {
        $email = $request->get('email');
        $password = $request->get('password');
        if(!$email && !$password){
            return $this->returnMsg('504','参数不能为空');
        }
        $payload = [   
            'email' => $email,  
            'password' => $password, 
        ];
        try {   
            if (!$token = JWTAuth::attempt($payload)) {   
                return response()->json(['error' => 'token_not_provided'], 401);  
            }   
        } catch (JWTException $e) {   
            return response()->json(['error' => '不能创建token'], 500);  
        }   
        $user = User::first();
        $user['now'] = time();
        $token = JWTAuth::fromUser($user);
 
        return $this->returnMsg('200','ok',$token);  
    }   

    /** 
     * @param Request $request 
     */  
    public function register(Request $request)  
    {  
        $input = $request->all();
        $validator = Validator::make($input, [
            'email' => 'required|min:3',
			'name' => 'required',
			'password' => 'required',
        ]);   
        if($validator->fails())
        {
            return $this->returnMsg('500', '参数不全');
        }
        $newUser = [  
            'email' => $request->get('email'),  
            'name' => $request->get('name'),  
            'password' => bcrypt($request->get('password'))  
        ];  
        $user = User::create($newUser);  
        $token = JWTAuth::fromUser($user);  
        return $this->returnMsg('200','ok',$token);  
    }  
}
